package com.estore.view;

import com.estore.model.Product;
import com.estore.service.ProductService;
import com.estore.service.ProductSorters;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.io.*;

public class ConsoleShop {

    private final ProductService productService = new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        showWelcomeInfo(); // 显示欢迎信息和配置信息

        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费掉换行符

            switch (choice) {
                case 1:
                    browseProducts(null); // 默认排序
                    break;
                case 2:
                    showSortedProducts(); // 自定义排序浏览商品
                    break;
                case 3:
                    addToCart();
                    break;
                case 4:
                    viewCart();
                    break;
                case 5:
                    showSystemInfo(); // 显示系统信息
                    break;
                case 6:
                    exit();
                    return;
                case 99: // 隐藏的管理员功能 - 数据备份
                    backupData();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    /**
     * 显示欢迎信息和配置信息
     */
    private void showWelcomeInfo() {
        System.out.println("\n===== 欢迎来到商城 =====");
        System.out.println("当前配置信息：");
        System.out.println("数据文件: " + productService.getDataFilePath());
        System.out.println("文件编码: " + productService.getFileEncoding());
        System.out.println("商品数量: " + productService.getProductCount());
        System.out.println("==========================");
    }

    private void showMenu() {
        System.out.println("\n===== 主菜单 =====");
        System.out.println("1. 浏览所有商品（默认排序）");
        System.out.println("2. 自定义排序浏览商品");
        System.out.println("3. 添加商品到购物车");
        System.out.println("4. 查看购物车");
        System.out.println("5. 显示系统信息");
        System.out.println("6. 退出");
        System.out.print("请输入您的选择: ");
        // 注意：隐藏选项99不会在菜单中显示
    }

    /**
     * 显示系统信息
     */
    private void showSystemInfo() {
        System.out.println("\n--- 系统信息 ---");
        System.out.println("数据文件路径: " + productService.getDataFilePath());
        System.out.println("文件编码: " + productService.getFileEncoding());
        System.out.println("当前商品数量: " + productService.getProductCount());
        System.out.println("购物车商品种类: " + shoppingCart.size());

        // 检查备份文件是否存在
        File backupFile = new File(productService.getDataFilePath() + ".bak");
        if (backupFile.exists()) {
            System.out.println("备份文件: " + backupFile.getName() + " (存在)");
            System.out.println("备份文件大小: " + backupFile.length() + " 字节");
            System.out.println("最后修改: " + new java.util.Date(backupFile.lastModified()));
        } else {
            System.out.println("备份文件: 暂无备份");
        }
    }

    /**
     * 数据备份功能
     * 使用基本的字节流和缓冲区进行文件复制
     */
    private void backupData() {
        String sourceFilePath = productService.getDataFilePath();
        String backupFilePath = sourceFilePath + ".bak";

        System.out.println("\n--- 开始数据备份 ---");
        System.out.println("源文件: " + sourceFilePath);
        System.out.println("备份文件: " + backupFilePath);

        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            System.out.println("错误：源数据文件不存在，无法备份！");
            return;
        }

        // 确认备份操作
        System.out.print("确定要备份数据吗？(y/N): ");
        String confirm = scanner.nextLine();
        if (!confirm.equalsIgnoreCase("y")) {
            System.out.println("备份操作已取消");
            return;
        }

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupFilePath)) {

            // 创建缓冲区，大小为1KB
            byte[] buffer = new byte[1024];
            int bytesRead;
            long totalBytes = 0;

            System.out.println("开始备份数据...");

            // 循环读取源文件并写入备份文件
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
                totalBytes += bytesRead;

                // 显示备份进度（每读取1MB显示一次）
                if (totalBytes % (1024 * 1024) == 0) {
                    System.out.println("已备份: " + (totalBytes / (1024 * 1024)) + " MB");
                }
            }

            // 确保所有数据都写入磁盘
            fos.flush();

            System.out.println("数据备份完成！");
            System.out.println("总备份大小: " + totalBytes + " 字节 (" +
                    (totalBytes / 1024.0) + " KB)");

            // 验证备份文件
            File backupFile = new File(backupFilePath);
            if (backupFile.exists() && backupFile.length() == sourceFile.length()) {
                System.out.println("✓ 备份文件验证成功");
            } else {
                System.out.println("⚠ 备份文件大小与源文件不一致，请检查备份完整性");
            }

        } catch (FileNotFoundException e) {
            System.err.println("错误：文件未找到 - " + e.getMessage());
        } catch (IOException e) {
            System.err.println("错误：备份过程中发生IO异常 - " + e.getMessage());
        }
    }

    private void showSortedProducts() {
        System.out.println("\n--- 请选择排序方式 ---");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.println("4. 返回主菜单");
        System.out.print("请输入您的选择: ");

        int sortChoice = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        Comparator<Product> comparator = null;
        String sortDescription = "";

        switch (sortChoice) {
            case 1:
                comparator = ProductSorters.BY_PRICE_ASC;
                sortDescription = "价格从低到高";
                break;
            case 2:
                comparator = ProductSorters.BY_PRICE_DESC;
                sortDescription = "价格从高到低";
                break;
            case 3:
                comparator = ProductSorters.BY_STOCK_DESC;
                sortDescription = "库存从多到少";
                break;
            case 4:
                return; // 返回主菜单
            default:
                System.out.println("无效的排序选项，使用默认排序");
        }

        if (comparator != null) {
            System.out.println("\n--- 商品列表（按" + sortDescription + "排序）---");
            browseProducts(comparator);
        } else if (sortChoice != 4) {
            browseProducts(null); // 默认排序
        }
    }

    private void browseProducts(Comparator<Product> comparator) {
        List<Product> products = productService.getAllProducts();

        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
            return;
        }

        // 根据是否传入Comparator来决定排序方式
        if (comparator != null) {
            // 使用自定义比较器排序
            products.sort(comparator);
        } else {
            // 使用自然排序（Product类的compareTo方法）
            java.util.Collections.sort(products);
        }

        // 显示商品列表
        products.forEach(System.out::println);
    }

    // 保留原有的无参方法，向后兼容
    private void browseProducts() {
        browseProducts(null);
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }

    /**
     * 退出程序，保存数据
     */
    private void exit() {
        System.out.println("正在保存商品数据...");
        if (productService.saveData()) {
            System.out.println("数据保存成功！文件位置: " + productService.getDataFilePath());

            // 询问是否在退出前自动备份
            System.out.print("退出前是否创建数据备份？(y/N): ");
            String backupChoice = scanner.nextLine();
            if (backupChoice.equalsIgnoreCase("y")) {
                backupData();
            }
        } else {
            System.out.println("数据保存失败，部分更改可能丢失！");
        }
        System.out.println("感谢使用，再见！");
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}